from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.utils.translation import gettext_lazy as _
from django.core.validators import FileExtensionValidator
from .services import (
    get_path_upload_avatar,
    get_path_upload_backgroundImg,
    validate_size_image,
)
import uuid


class User(AbstractUser):
    """ Custom user model
    """
    REQUIRED_FIELDS = ['username']
    USERNAME_FIELD = 'email'
    username_validator = UnicodeUsernameValidator()

    is_activated = models.BooleanField(default=False, db_index=True, verbose_name=_("is activated?"))
    send_message = models.BooleanField(default=True, verbose_name=_("send messages?"))
    email = models.EmailField(max_length=150, unique=True)
    join_date = models.DateTimeField(auto_now_add=True)
    country = models.CharField(max_length=30, blank=True, null=True, verbose_name=_("country"))
    city = models.CharField(max_length=30, blank=True, null=True, verbose_name=_("city"))
    about = models.TextField(max_length=2000, blank=True, null=True)
    username = models.CharField(
        max_length=30, blank=True, null=True, verbose_name=_("username"), validators=[username_validator],
        error_messages={'unique': _("A user with that username already exists.")}
    )
    display_name = models.CharField(max_length=40, blank=True, null=True, verbose_name=_("display name"))
    avatar = models.ImageField(
        upload_to=get_path_upload_avatar,
        blank=True,
        null=True,
        verbose_name=_("avatar"),
        validators=[FileExtensionValidator(allowed_extensions=['jpg', 'png', 'jpeg']), validate_size_image]
    )
    background_image = models.ImageField(
        upload_to=get_path_upload_backgroundImg,
        blank=True,
        null=True,
        verbose_name=_('background'),
        validators=[FileExtensionValidator(allowed_extensions=['jpg', 'png', 'jpeg', 'JPG', 'JPEG']), validate_size_image]
    )

    def __str__(self):
        return f'{self.username} - {self.city}'

    class Meta:
        verbose_name = 'Пользователь'
        verbose_name_plural = 'Пользователи'
        ordering = ['-join_date',]


class ArchiveUsers(models.Model):
    """ All registered users data """
    user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    email = models.EmailField()
    date_join = models.DateField(auto_now_add=True)
    date_leave = models.DateField(blank=True, null=True)

    class Meta:
        verbose_name = 'Архив - Пользователь'
        verbose_name_plural = 'Архив - Пользователи'

    def __str__(self):
        return f'{self.email} join: {self.date_join}'